﻿using System.Text;
using CcrFlows;
using Microsoft.Ccr.Core;

namespace SampleFlow
{
    class AssembleLineFromWords : ISeqHandler<string, string>
    {
        private readonly int maxLineLength;
        private StringBuilder currentLine;

        public AssembleLineFromWords(int maxLineLength)
        {
            this.maxLineLength = maxLineLength;
            this.currentLine = new StringBuilder();
        }


        #region Implementation of ISeqHandler<string,string>

        public void Handle(string word, Port<string> lines)
        {
            if (word == null)
                WriteFinalLine(lines);
            else
            {
                WriteLineIfFull(word, lines);
                AppendWordToLine(word);
            }
        }


        private void WriteFinalLine(Port<string> lines)
        {
            lines.Post(this.currentLine.ToString());
            lines.Post(null);
        }

        private void WriteLineIfFull(string word, Port<string> lines)
        {
            if (this.currentLine.Length + word.Length + 1 >= this.maxLineLength)
            {
                lines.Post(this.currentLine.ToString());
                this.currentLine = new StringBuilder();
            }
        }

        private void AppendWordToLine(string word)
        {
            if (this.currentLine.Length > 0) this.currentLine.Append(" ");
            this.currentLine.Append(word);
        }
        #endregion
    }
}
